Find the Sum of Natural Numbers Using Recursion

Course- R Programming >

Here, we ask the user for a number and use recursive function recur_sum() to compute the sum upto that number.

Source Code

# Program to find the sum of
# natural numbers upto n
# using recursive function

recur_sum <- function(n) {
    if(n <= 1) {
        return(n)
    } else {
        return(n + recur_sum(n-1))
    }
}

Output


> recur_sum(7)
[1] 28